package mips.instructions;

/**
 * <code>SLTI</code> instruction<br/>
 * Set On Less Than Immediate<br/>
 * @author jnmartin84@gmail.com
 */
public class SLTI extends Instruction {

	private static final SLTI INSTANCE = new SLTI();
	private static final String INSTRUCTION_NAME = "SLTI";

	private SLTI(){}

	public static final SLTI getInstance() {
		return INSTANCE;
	}

	/**
	 * <b>Format:</b><br/>
	 * SLTI rt, rs, immediate<br/><br/>
	 * <b>Description:</b><br/>
	 * The 16-bit immediate is sign-extended and subtracted from the contents of<br/>
	 * general register rs. Considering both quantities as signed integers, if rs is<br/>
	 * less than the sign-extended immediate, the result is set to one; otherwise<br/>
	 * the result is set to zero.<br/><br/>
	 * The result is placed into general register rt.<br/><br/>
	 * No integer overflow exception occurs under any circumstances. The<br/>
	 * comparison is valid even if the subtraction used during the comparison<br/>
	 * overflows.<br/><br/>
	 * <b>Operation:</b><br/>
	 * T: if GPR[rs] < (immediate<sub>15</sub>)<sup>16</sup> || immediate<sub>15...0</sub> then<br/>
	 * GPR[rt] &larr; 0<sup>31</sup> || 1<br/>
	 * else<br/>
	 * GPR[rt] &larr; 0<sup>32</sup><br/>
	 * endif
	 */
	@Override
	public final void execute(final int instruction) {
		
		final int rs = (instruction >> 21) & 0x0000001F;
		final int rt = (instruction >> 16) & 0x0000001F;
		final int immed = Instruction.signExtendH((instruction) & 0x0000FFFF);

		mips.R4300i.GPR[rt] = (mips.R4300i.GPR[rs] < immed) ? 1 : 0;
		
		mips.R4300i.PC = mips.R4300i.nPC;
		mips.R4300i.nPC = mips.R4300i.PC + 4;		
	}
	
	/**
	 * {@inheritDoc}
	 */
	@Override
	public final String emit(final int instruction) {
		
		final int rs = (instruction >> 21) & 0x0000001F;
		final int rt = (instruction >> 16) & 0x0000001F;
		final int immed = Instruction.signExtendH((instruction) & 0x0000FFFF);
		
		return	"		mips.CPU.GPR["+rt+"] = (mips.CPU.GPR["+rs+"] < "+immed+") ? 1 : 0;\n" + 
				"		\n" + 
				"		mips.CPU.PC = mips.CPU.nPC;\n" + 
				"		mips.CPU.nPC = mips.CPU.PC + 4;\n";
	}
	
	/**
	 * {@inheritDoc}
	 */
	@Override
	public final String getName(final int instruction) {
		return getName();
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public final String getName() {
		return INSTRUCTION_NAME;
	}
}